function newFile = UnsliceDicom( folderPath, fileNames)
% Read every .IMA file in the input folder, create a new niftii file
% and put it in the same folder, returns the path to the file.
for i=1:length(fileNames)
    fileNames{i} = fullfile(folderPath,fileNames{i});
end

headers = icem_spm_dicom_headers(fileNames);

validIndex = -1;
list = cell(0);
sequencesNumber = 0;
tag = '';
previousSeriesNumber = -1;
previousAcquisitionNumber = -1;
for i=1:length(headers)
    if ~isfield(headers{i}, 'SeriesNumber')
        continue;
    else
        validIndex = i;
    end
    if  (~strcmp(headers{i}.StudyID,tag)  ||...
            headers{i}.SeriesNumber ~= previousSeriesNumber)%...
            %(isfield(headers{i},'AcquisitionNumber') && headers{i}.AcquisitionNumber ~= previousAcquisitionNumber))
        %headers{i}.InstanceNumber == 1
        tag= headers{i}.StudyID;
        previousSeriesNumber = headers{i}.SeriesNumber;
        if isfield(headers{i},'AcquisitionNumber')
            previousAcquisitionNumber = headers{i}.AcquisitionNumber;
        end
        sequencesNumber = sequencesNumber +1 ;
        list{sequencesNumber} = i;
    else
        list{sequencesNumber} = [list{sequencesNumber} i];
    end
end
info=dicominfo(fileNames{validIndex});
i=1;
while i<=length(list)
   if length(list{i})<2
       list(i) = [];
   else
       i=i+1;
   end
end
choicesAvailable=cell(length(list),1);
for i=1:length(list)
    choicesAvailable{i}=[headers{list{i}(1)}.StudyDescription '-'...
       headers{list{i}(1)}.SeriesDescription '- ('...
       num2str(length(list{i})) ' slices)'];
end
choice = 1;
if length(choicesAvailable)>1 
choice = menu ('Please select the series you whish to open',choicesAvailable);
end
fileNames = fileNames(list{choice});
% for i=1:length(fileNames)
%     fileNames{i} = fullfile(folderPath,fileNames{i});
% end

headers = icem_spm_dicom_headers(fileNames);
%[status,attrib] = fileattrib(folderPath);
previousDir = cd;
%if (~attrib.UserWrite)
    folder = uigetdir(previousDir,'Please select a folder with write access.');
   % [status,attrib] = fileattrib(folder);
    while folder(1)==0 || (~exist(folder,'dir'))% || ~attrib.UserWrite
        folder = uigetdir(previousDir,'Please select a folder with write access.');
    end
cd(folder);
newFile = spm_dicom_convert(headers,'all','flat','nii');
newFile = newFile.files{1};


if isfield(info.PatientName,'FamilyName')
    familyName=info.PatientName.FamilyName;
else
    familyName = 'XXX';
end

if isfield(info.PatientName,'GivenName')
    firstName=info.PatientName.GivenName;
else
    firstName = 'XXX';
end

age=sscanf(info.PatientAge, '%dY');
%birthDate=info.PatientBirthDate;
acquisitionDate=info.AcquisitionDate;
%sex=info.PatientSex;
studyTime=strcat(info.StudyTime(1:2),'h',info.StudyTime(3:4));

%replace '.' and ' ' with '_'
familyName = regexprep(familyName, '[ .]', '_');
familyName = fixedLength(familyName, 3, '_');
firstName = regexprep(firstName, '[ .]', '_');
firstName = fixedLength(firstName, 2, '_');

% Building name for the new NIfTI file:
newNIfTI=strcat(familyName,'_', firstName, '_', acquisitionDate, '_', ...
    studyTime, '_', num2str(age));
% Creating full path for the new NIfTI :
NIfTIPath = fullfile(cd, [newNIfTI '.nii']);

% saving DICOM header in the destination folder
save(fullfile(cd,['header' newNIfTI '.mat']),'info');
movefile(newFile,NIfTIPath,'f');
newFile = NIfTIPath;
%[pathstr, name, ext, versn] = fileparts(newFile);
%copyfile(newFile, fullfile(folderPath,[name ext]));
%newFile = fullfile(folderPath,[name ext]);
header = spm_vol(newFile);
vol = spm_read_vols(header);
header.mat(1:3,4) = zeros(1,3);
header.mat(:,4) = -(header.mat*[(header.dim/2)';-1]);
spm_write_vol(header,vol);
cd (previousDir);
end



%==========================================================================
% UTILITY FUNCTIONS
%==========================================================================

% fixed length takes the first N letters of input strings. If the string
% contains less thant N characters, fills with char fillingChar
function strOut = fixedLength(str, N, fillingChar)
    str = upper(str);
    if length(str) > N
        str = str(1:N);
    else
        while length(str) < N
            str = strcat(str,fillingChar);
        end
    end
    strOut = str;
end

